﻿'use strict';

function MainCtrl($scope, $rootScope, $dialog, $window, CartService, CatalogService, IncentiveService, AccountService) {

    LoadCart($rootScope, null, CartService, IncentiveService);

    CatalogService.getCategoryList().then(function (response) {
        $scope.categoryList = response.data;
    });

    AccountService.getUserInfo().then(function (response) {
        $rootScope.user = response.data;
    });

    $rootScope.addToCart = function (product, quantity) {

        var opts = {
            backdrop: true,
            keyboard: true,
            backdropClick: true,
            templateUrl: '/ngviews/cart/addtocart.html',
            controller: 'AddToCartCtrl',
            resolve: { item: function () { return { product: product, quantity: quantity, cart : $scope.cart }; } }
        };

        var d = $dialog.dialog(opts);
        d.open();
    }

    var rootBreadcrumb = { Name: "Home", Url: "/#!/home", Title: "Home page" };
    $scope.resetBreadcrumbs = function () {
        $scope.breadcrumbs = [];
        $scope.breadcrumbs.push(rootBreadcrumb);
    };
    $scope.resetBreadcrumbs();

    $scope.search = function () {
        $window.location.href = '/#!/search/' + $scope.query;
    };
}

function HomeController($scope, $routeParams, OfferService ) {
    var filter = {
        offerLink: 'offer_of_the_year'
    };
    OfferService.getProductList(filter).then(function (response) {
        $scope.productList = response.data;
    });

    $scope.resetBreadcrumbs();
}

function CategoryController($scope, $routeParams, CatalogService) {

    $scope.resetBreadcrumbs();

    var filter = {
        PageIndex: 0,
        PageSize: 20,
        ProductCategoryId: null
    }

    CatalogService.getCategoryByLink($routeParams.link).then(function (response) {
        $scope.category = response.data;
        filter.ProductCategoryId = $scope.category.Id;
        $scope.nextpage();
    });
    
    $scope.productList = [];
    $scope.nextpage = function() {
        if ($scope.busy) return;
        $scope.busy = true;

        if ($scope.productList.length >= $scope.TotalCount) {
            return;
        }

        var p = Math.ceil($scope.productList.length / filter.pageSize);
        filter.PageIndex = p;
        CatalogService.getProductList(filter).then(function (response) {
            for (var i = 0; i < response.data.List.length; i++) {
                var product = response.data.List[i];
                $scope.productList.push(product);
            }
            $scope.totalCount = response.data.TotalCount;
        });

        $scope.busy = false;
    }
}

function SearchController($scope, $routeParams, CatalogService) {

    $scope.resetBreadcrumbs();
    $scope.query = $routeParams.query;

    var filter = {
        PageIndex: 0,
        PageSize: 20,
        Search : $routeParams.query
    }

    $scope.productList = [];
    $scope.nextpage = function () {
        if ($scope.busy) return;
        $scope.busy = true;

        if ($scope.productList.length >= $scope.TotalCount) {
            return;
        }

        var p = Math.ceil($scope.productList.length / filter.pageSize);
        filter.PageIndex = p;
        CatalogService.getProductList(filter).then(function (response) {
            for (var i = 0; i < response.data.List.length; i++) {
                var product = response.data.List[i];
                $scope.productList.push(product);
            }
            $scope.totalCount = response.data.TotalCount;
        });

        $scope.busy = false;
    }

    $scope.nextpage();
}

function ProductController($scope, $rootScope, $routeParams, $window, CatalogService, OfferService) {
    CatalogService.getProductByCode($routeParams.code).then(function (response) {
        $scope.product = response.data;
        $window.document.title = $scope.product.PageTitle;
        $scope.resetBreadcrumbs();
        $scope.breadcrumbs.push({ Name: $scope.product.Category.Name, Url: '/#!/category/' + $scope.product.Category.Link });
    });
    $scope.quantity = 1;

    var filter = {
        offerLink: 'special_offer_camera'
    };
    OfferService.getProductList(filter).then(function (response) {
        $scope.specialProductList = response.data;
    });
}

function AddToCartCtrl($scope, $rootScope, dialog, item, CartService, IncentiveService) {
    $scope.product = item.product;
    $scope.quantity = item.quantity;
    $scope.save = function () {
        CartService.addToCart(item.product, item.quantity).then(function(response){
            LoadCart($rootScope, $rootScope.cart.Code, CartService, IncentiveService);
        });
        dialog.close();
    }
    $scope.cancel = function () {
        dialog.close();
    }
}

function CartController($scope, $rootScope, $routeParams, CartService, IncentiveService) {

    if ($rootScope.cart.Code != $routeParams.cartCode) {
        // View external cart
        LoadCart($scope, $routeParams.cartCode, CartService);
    }

    $scope.couponError = null;
    $scope.applyCoupon = function (couponCode) {
        if (couponCode == null || couponCode == "") {
            alert('coupon must be not null or empty');
            return;
        }
        $scope.checkCouponProgressMessage = 'Check coupon in progress';
        IncentiveService.applyCoupon(couponCode, $rootScope.cart.Code).then(function (response) {
            // console.log(response);
            var result = response.data.valueOf(0)[0];
            // console.log(result);
            if (result != null && result.ErrorList != null) {
                $scope.couponError = result.ErrorList[0];
            } else {
                LoadCart($scope, $routeParams.cartCode, CartService, IncentiveService);
            }
            $scope.checkCouponProgressMessage = null;
        });
    };
}



function LoadCart($scope, cartCode, CartService, IncentiveService) {
    console.log('load cart (' + cartCode + ')');
    CartService.getCurrent(cartCode).then(function (response) {
        // console.log(response);
        $scope.cart = response.data;
        $scope.cart.changeQuantity = function (index, cartItem) {
            if (cartItem.Quantity < 1) {
                cartItem.Quantity = 1;
            }
            CartService.changeQuantity(index, cartItem).then(function (response) {
                LoadCart($scope, $scope.cart.Code, CartService, IncentiveService);
            });
        };
        $scope.cart.deleteItem = function (index) {
            CartService.deleteItem(index).then(function (response) {
                LoadCart($scope, $scope.cart.Code, CartService, IncentiveService);
            });
        };
        $scope.cart.deleteCoupon = function (coupon) {
            IncentiveService.removeCoupon(coupon.Code).then(function (response) {
                LoadCart($scope, $scope.cart.Code, CartService, IncentiveService);
            });
        };

        /*
        console.log('cart loaded ' + $scope.cart.Code);
        if ($scope.cart.Items != null) {
            console.log($scope.cart.Items.length + ' items');
        }*/
    });
}